<template>
  <el-drawer
    v-model="dialogFormVisible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :size="600"
    :title="title"
    @close="close"
  >
    <div class="drawer__content drawer-content userForm-div">
      <el-form
        ref="formRef"
        :hide-required-asterisk="true"
        label-position="right"
        label-suffix="："
        label-width="120px"
        :model="form"
        :rules="rules"
        style="margin-left: 10px;width:80%;"
      >
        <el-form-item label="用户" prop="name">
          <el-input
            v-model.trim="form.name"
            auto-complete="new-password"
            :disabled="isEdit"
            maxlength="20"
            size="20"
          />
          <!-- @input="(e) => (form.name = validForbid(e))" -->
          &nbsp;
          <font color="red">*</font>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="userPwd">
          <el-input
            v-model="form.userPwd"
            maxlength="32"
            size="32"
            type="password"
            @copy.capture.prevent="handleFalse"
            @cut.capture.prevent="handleFalse"
            @paste.capture.prevent="handleFalse"
          />
          &nbsp;
          <font color="red">*</font>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="surePwd">
          <el-input
            v-model="form.surePwd"
            maxlength="32"
            size="32"
            type="password"
            @copy.capture.prevent="handleFalse"
            @cut.capture.prevent="handleFalse"
            @paste.capture.prevent="handleFalse"
          />
          &nbsp;
          <font color="red">*</font>
        </el-form-item>
       
        <el-form-item label="手机号">
          <el-form-item prop="tel">
            <el-input v-model="form.tel" maxlength="11" size="11" />
            <!-- &nbsp;
            <font color="red">*</font> -->
          </el-form-item>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-form-item prop="email">
            <el-input v-model="form.email" maxlength="40" size="40" />
          </el-form-item>
        </el-form-item>
        <el-form-item label="所属部门" prop="pid">
        <el-select v-model="form.deptId" placeholder="所属部门">
          <el-option v-for="item in allDeptData" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
        <!-- <el-form-item label="所属部门">
          <div class="role-content">
            <ul class="role-content-tab">
              <el-scrollbar
                style="
                  height: 350px;
                  width:400px;
                  background: #fbfbfb;
                  border: 1px solid #dbdbdb;
                  border-radius: 4px;
                "
              >
              <div class="showDepartTree">
        <el-input class="treeFilter" v-model="keyword" placeholder="查询节点" :suffix-icon="Search" />
            <el-tree ref="treeRef" :data="treeData"  :default-expanded-keys="checkedArr" :default-checked-keys="checkedArr"
            show-checkbox  node-key="id" :props="defaultProps" :default-expand-all="true" :filter-node-method="filterNode" />
         </div>
              </el-scrollbar>
            </ul>
          </div>
        </el-form-item> -->
      </el-form>
      <div class="drawer__footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts">
  import {
    updateUser,
    addUser,
    getUserInfo,
    queryUserRoleList,
  } from '@/api/system/user'
  import { getAllTreeData ,getAllList } from '@/api/depart'
  import {
    validPwdLow,
    validChinese,
    validPhone,
    validEmail,
  } from '@/utils/validate'
  import aes from '@/utils/aes.js'
  import {Base64} from 'js-base64'
  import { ElMessage, ElMessageBox } from 'element-plus'

  // const Base64 = require('js-base64').Base64
  export default defineComponent({
    name: 'UserEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const validatePassword = (rule, value, callback) => {
        if (value !== '' && !validPwdLow(value)) {
          callback(
            new Error(
              '密码长度为8~32个字符须包含大小写英文字母及特殊字符!@~#%&*'
            )
          )
        } else {
          callback()
        }
      }
      const validateCh = (rule, value, callback) => {
        if (value !== '' && validChinese(value)) {
          callback(new Error('用户名称不可以包含中文'))
        } else {
          callback()
        }
      }
      const checkPhone = (rule, value, callback) => {
        if (state.isEdit && dataFilter(state.tempPhone) === value) {
          callback()
        } else {
          if (value !== undefined && value !== '') {
            if (!validPhone(value)) {
              callback(new Error('请输入正确的手机号码'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      }
      const checkEmail = (rule, value, callback) => {
        if (state.isEdit && dataFilter(state.tempEmail) === value) {
          callback()
        } else {
          if (value !== undefined && value !== '') {
            if (!validEmail(value)) {
              callback(new Error('请输入正确的邮箱'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      }
      const state = reactive({
        allDeptData:[],
        checkedArr:[],
        treeRef:null,
        keyword:'',
        formRef: null,
        treeData:[],
        roles: [],
        isEdit: false,
        tempPhone: '',
        tempEmail: '',
        form: {
          id: null,
          name: '',
          userPwd: '',
          surePwd: '',
          phone: '',
          email: '',
          deptId: '',
        },
        checkVal: [],
        rules: {
          name: [
            {
              required: true,
              trigger: ['blur', 'change'],
              message: '请输入用户名',
            },
            { trigger: ['blur', 'change'], validator: validateCh },
          ],
          userPwd: [
            {
              required: true,
              trigger: ['blur', 'change'],
              message: '请输入密码',
            },
            { trigger: ['blur', 'change'], validator: validatePassword },
          ],
          surePwd: [
            {
              required: true,
              trigger: ['blur', 'change'],
              message: '请输入确认密码',
            },
            { trigger: ['blur', 'change'] },
          ],
          phoneNumber: [
            // {
            //   required: true,
            //   trigger: ['blur', 'change'],
            //   message: '请输入手机号码',
            // },s
            { trigger: ['change'], validator: checkPhone },
          ],
          email: [
            // {
            //   required: true,
            //   trigger: ['blur', 'change'],
            //   message: '请输入邮箱',
            // },
            { trigger: ['change'], validator: checkEmail },
          ],
        },
        title: '',
        dialogFormVisible: false,
        defaultProps:{
        children: 'children',
        label: 'name',
      }
      })

    const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.name.includes(value)
    }
    const getAllData=async()=>{
      getAllTreeData().then(res => {
        state.treeData=res.data||[]
        console.log(res,"~~getAllTreeData~~~rrrrrrr~~~")
      })
    }
    const getAllDept=async()=>{
  getAllList().then(res => {
    state.allDeptData=res.data||[]
    console.log(state.allDeptData,"~~allDeptData~~~allDeptData~~~")
   })
}
      const dataFilter = (val) => {
        const re = val
        const reg = /^(.{3}).*(.{3})$/
        return re.replace(reg, '$1****$2')
      }
      const handleFalse = () => {
        return false
      }
      const validForbid = (value) => {
        value = value
          .replace(
            /[`~@#$%^&*-+=<>?"{}|;'\\[\]~！：（）·，。【】,.\\/\-_()!@#￥%……&*——+={}|《》？“”、；‘’、]/g,
            ''
          )
          .replace(/\s/g, '')
        return value
      }
      const showEdit = (row) => {
        state.checkVal = []
        getAllDept()
        if (!row) {
          state.title = '添加'
          state.isEdit = false
          // getRoleList()
        } else {
          state.title = '编辑'
          state.checkedArr = []
          state.isEdit = true
          getUserDetail(row)
        }
        state.dialogFormVisible = true
      }
      const getUserDetail = (row) => {
        getUserInfo({ id: row.id }).then((response) => {
          const tmpObj = response.data
          // tmpObj.userPwd = ''
          // tmpObj.surePwd = ''
          // if (tmpObj.phoneNumber !== '') {
          //   state.tempPhone = aes.decrypt(
          //     Base64.decode(tmpObj.phoneNumber),
          //     aes.rightPad(tmpObj.username + '#17tel', 32, aes.keyM)
          //   )
          //   tmpObj.phoneNumber = dataFilter(state.tempPhone) // aes.decrypt(Base64.decode(tmpObj.phoneNumber), aes.rightPad(tmpObj.username + '#17tel', 32, aes.keyM))
          // }
          // if (tmpObj.email !== '') {
          //   state.tempEmail = aes.decrypt(
          //     Base64.decode(tmpObj.email),
          //     aes.rightPad(tmpObj.username + '#17mail', 32, aes.keyM)
          //   )
          //   tmpObj.email = dataFilter(state.tempEmail) // aes.decrypt(Base64.decode(tmpObj.email), aes.rightPad(tmpObj.username + '#17mail', 32, aes.keyM))
          // }

          state.form = tmpObj
          // if (state.form.roles !== '') {
          //   var tmp = state.form.roleIds
          //   for (const role of tmp) {
          //     state.checkVal.push(parseInt(role))
          //   }
          // }
          // getRoleList()
          nextTick(() => {
            state.formRef.clearValidate()
          })
        })
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          id: null,
          username: '',
          userPwd: '',
          surePwd: '',
          phone: '',
          email: '',
          deptId: '',
        }
        state.dialogFormVisible = false
      }
      const handleFormObject = () => {
        const submitData = Object.assign({}, state.form)
        // submitData['deptId']=state.checkedArr.join(',')
        // if(state.checkedArr.length===0){
        //   ElMessage.error('密码和确认密码输入一致')
        // }
        // if (submitData.userPwd !== submitData.surePwd) {
        //   ElMessage.error('密码和确认密码输入一致')
        //   return false
        // }
       

        return submitData
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const paraObj = handleFormObject()
            if (paraObj) {
              // if (state.isEdit) {
              //   const { code } = await updateUser(paraObj)
              //   if (code === 1) {
              //     $baseMessage('操作成功', 'success', 'vab-hey-message-success')
              //     emit('fetch-data')
              //     close()
              //   }
              // } else {
                const { code } = await addUser(paraObj)
                if (code === 1) {
                  ElMessage.success('操作成功')
                  emit('fetch-data')
                  close()
                }
              // }
            }
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
        validForbid,
        handleFalse,
      }
    },
  })
</script>
<style lang="scss">
  .role-content-tab .el-scrollbar .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .userForm-div{
    .el-input {
      width:90%;
    }
    .el-form-item {
    margin-bottom: 28px;
    }
    .el-form-item__content{
      height:32px;
    }
  }
  .drawer__footer {
    text-align: center;
    position: absolute;
    bottom: 30px;
    width: 100%;
}
</style>
<style lang="scss" scoped>
  .role-content {
    width: 253px;
    min-height: 100px;
    .role-content-col {
      width: 110px;
      padding-left: 10px;
      text-align: left;
    }
    .role-content-head {
      margin-top: 10px;
      font-size: 13px;
      color: #fff;
      background: #000;
      border: 1px solid #000;
    }
    .role-content-tab {
      // margin-top: 0px;
      // margin-left: -40px;
      margin-top: 0px;
      margin-bottom: 0px;
      padding-left: 0px;
      color: #000;
      li {
        .opt {
          color: #08c;
          cursor: pointer;
        }
        .role-content-col-input {
          width: 120px;
        }
        .tmp {
          & > .el-input {
            width: 130px !important;
          }
        }
        &:hover {
          background: #f0f0f0;
        }
      }
    }
  }
</style>
